const sequelize = require('../../config/database');
const { QueryTypes } = require('sequelize');
const { CollectionModel } = require('../../models/index');

// 添加/取消收藏
const toggleCollection = async (req, res) => {
  try {
    // 获取得到的收藏数据
    const { user_id, association_id, type } = req.body

    if (!user_id || !association_id || !type) {
      return res.status(400).json({
        error: '收藏数据不能为空'
      })
    }

    // 查找是否已经存在该收藏记录
    const findCollection = await CollectionModel.findOne({
      where: {
        user_id: user_id,
        association_id: association_id,
        type: type
      }
    })

    if (findCollection) {
      await findCollection.destroy()
      return res.status(200).json({
        title: '取消收藏成功'
      })
    } else {
      // 添加收藏
      const addCollectionData = await CollectionModel.create({
        user_id: user_id,
        association_id: association_id,
        type: type
      })

      // 返回收藏成功的响应
      res.status(200).json({
        title: '添加收藏成功',
        data: addCollectionData.collection_id
      })
    }
  } catch (error) {
    res.status(500).json({
      error: error.message
    })
  }
}

// 查询收藏状态
const isCollected = async (req, res) => {
  try {
    // 获取需要查询的收藏数据
    const { user_id, association_id, type } = req.query

    if (!user_id || !association_id || !type) {
      return res.status(400).json({
        error: '收藏数据不能为空'
      })
    }

    // 查找是否已经存在该收藏记录
    const isCollected = await CollectionModel.findOne({
      where: {
        user_id: user_id,
        association_id: association_id,
        type: type
      }
    })

    // 根据查询结果返回收藏状态
    if (isCollected) {
      return res.status(200).json({
        title: '已经收藏',
        collected: true
      })
    } else {
      res.status(200).json({
        title: '未收藏',
        collected: false
      })
    }
  } catch (error) {
    res.status(500).json({
      error: error.message
    })
  }
}

// 获取用户收藏数据
const getUserCollectedData = async (req, res) => {
  try {
    // 获取用户ID
    const userID = req.params.user_id

    // 获取用户筛选条件,判断筛选的是商品数据还是攻略数据
    const is_post = req.query.is_post

    if (!userID) {
      return res.status(400).json({
        error: '用户ID不能为空'
      })
    }

    if (!is_post) {
      return res.status(400).json({
        error: '筛选条件不能为空'
      })
    }

    // 查询商品的SQL语句
    const queryGoodsSQL = `
SELECT
	sub.*,
	city.name city_name
FROM
	(
	SELECT
		c.collection_id,
    c.user_id,
    c.association_id,
    c.type,
	CASE
			c.type
			WHEN 'scenery' THEN
			s.name
			WHEN 'hotel' THEN
			h.name
			WHEN 'restaurant' THEN
			r.name ELSE NULL
		END AS name,
	CASE
			c.type
			WHEN 'scenery' THEN
			s.rating
			WHEN 'hotel' THEN
			h.rating
			WHEN 'restaurant' THEN
			r.rating ELSE NULL
		END AS rating,
	CASE
			c.type
			WHEN 'scenery' THEN
			s.grade
			WHEN 'hotel' THEN
			h.grade ELSE NULL
		END AS grade,
	CASE
			c.type
			WHEN 'scenery' THEN
			s.images
			WHEN 'hotel' THEN
			h.images
			WHEN 'restaurant' THEN
			r.images ELSE NULL
		END AS images,
	CASE
			c.type
			WHEN 'scenery' THEN
			s.price
			WHEN 'hotel' THEN
			h.price
			WHEN 'restaurant' THEN
			r.price ELSE NULL
		END AS price,
	CASE
			c.type
			WHEN 'scenery' THEN
			s.type
			WHEN 'hotel' THEN
			h.type
			WHEN 'restaurant' THEN
			r.type ELSE NULL
		END AS association_type,
	CASE
			c.type
			WHEN 'scenery' THEN
			s.city_id
			WHEN 'hotel' THEN
			h.city_id
			WHEN 'restaurant' THEN
			r.city_id ELSE NULL
		END AS city_id
	FROM
		collection c
		LEFT JOIN scenery s ON c.association_id = s.scenery_id
		AND c.type = 'scenery'
		LEFT JOIN hotel h ON c.association_id = h.hotel_id
		AND c.type = 'hotel'
		LEFT JOIN restaurant r ON c.association_id = r.restaurant_id
		AND c.type = 'restaurant'
	) sub
	LEFT JOIN city ON sub.city_id = city.city_id
WHERE
	user_id = :UserID
	AND sub.type != 'post';
    `

    // 查询攻略的SQL语句
    const queryPostSQL = `
SELECT
	sub.*,
	user.username,
	user.avatar
FROM
	(
	SELECT
		c.collection_id,
		c.user_id,
		c.association_id,
		c.type,
		p.title,
		p.images,
		p.createdAt
	FROM
		collection c
		LEFT JOIN post p ON c.association_id = p.post_id
		AND c.type = 'post'
	) sub
	LEFT JOIN user ON sub.user_id = user.user_id
WHERE
	sub.user_id = :UserID
	AND sub.type = 'post';
    `

    // 将数据转化为前端需要的格式
    let formQueryData = {}

    // 返回收藏的商品数据或者攻略数据
    if (is_post === 'true') {
      const queryPostData = await sequelize.query(queryPostSQL, { type: QueryTypes.SELECT, replacements: { UserID: userID } })
      formQueryData = queryPostData.map(item => {
        return {
          id: item.association_id,
          type: item.type,
          title: item.title,
          image: item.images.slice(0, 1)[0].url,
          createdAt: item.createdAt,
          user: {
            username: item.username,
            avatar: item.avatar
          },
          collected_id: item.collection_id
        }
      })
      res.status(200).json({
        title: '用户收藏的攻略数据',
        data: formQueryData
      })
    } else {
      const queryGoodsData = await sequelize.query(queryGoodsSQL, { type: QueryTypes.SELECT, replacements: { UserID: userID } })
      formQueryData = queryGoodsData.map(item => {
        return {
          id: item.association_id,
          type: item.type,
          name: item.name,
          rating: item.rating,
          grade: item.grade,
          image: item.images[0].url,
          price: item.price,
          association_type: item.association_type,
          city_name: item.city_name,
          collected_id: item.collection_id,
        }
      })
      res.status(200).json({
        title: '用户收藏的商品数据',
        data: formQueryData
      })
    }



  } catch (error) {
    res.status(500).json({
      error: error.message
    })
  }
}

module.exports = {
  toggleCollection,
  isCollected,
  getUserCollectedData
}